package com.jhws.sys.user.service;

import com.jhws.core.db.BaseDao;
import com.jhws.sys.cms.service.AppResourceService;
import com.jhws.sys.user.bo.UserCommsBo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 用户与小区映射表的操作服务,一个用户小可能管辖多个小区
 */
@Service
public class UserCommsService {

    @Resource
    BaseDao BaseDao;
    @Resource
    private AppResourceService appResourceService;

    /**
     * 通过名称查找usercomms
     *
     * @param userName
     * @return
     */
    public List<UserCommsBo> findUserCommsByName(String userName) {
        return BaseDao.findList("from UserCommsBo where user_name = '" + userName + "'");
    }

    /**
     * 查找出user名下所有的绑定小区的名称及编号
     * @param userName
     * @return
     */
    public List<Map> findUserCommDetailsByName(String userName){
        return BaseDao.findList("select new map(comm.commCode as commCode,comm.commName as commName) from UserCommsBo as uc,TblCommDimBo as comm " +
                "where uc.userName = '"+userName+"' and uc.commCode = comm.commCode");
    }

    /**
     * 通过where语句查找
     *
     * @param where
     * @return
     */
    public List<UserCommsBo> findUserCommsByWhere(String where) {
        return BaseDao.findList("from UserCommsBo " + where);
    }

    /**
     * 通过名称删除
     *
     * @param userName
     * @throws Exception
     */
    public void removeByName(String userName) throws Exception {
        //先清除CMS在删除
        List<UserCommsBo> userCommsBos = findUserCommsByName(userName);
        for (UserCommsBo userCommsBo : userCommsBos) {
            removeCMSResource(userName, userCommsBo.getCommCode());
        }
        BaseDao.deleteByColumns("UserCommsBo", "user_name", userName);
    }

    /**
     * 通过小区删除
     *
     * @param commCode
     * @throws Exception
     */
    public void removeByCommCode(String userName, String commCode) throws Exception {
        BaseDao.deleteByWhere("UserCommsBo", "user_name = '" + userName + "' and comm_code = '" + commCode + "'");
        removeCMSResource(userName, commCode);
    }

    /**
     * 查找某个username的数据条数，就是查找某个用户下有多少个小区
     *
     * @param userName
     * @return
     */
    public Long getCommCountByName(String userName) {
        return BaseDao.getCountByHql("select count(*) from UserCommsBo where user_name = '" + userName + "'");
    }

    /**
     * 存储
     *
     * @param bo
     * @return
     */
    public void save(UserCommsBo bo) {
        BaseDao.saveOrUpdate(bo);
    }

    /**
     * 移除小区分配的cms资源
     */
    private void removeCMSResource(String userName, String commCode) {
        appResourceService.deleteResource(" where creator='" + userName + "' and comm_code='" + commCode + "'");
    }
}
